//============================================
// B_NC_electric_meter
// 2015-01-23 
//============================================
#include <stdlib.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <wiringPi.h>
#include <time.h>
#include <string.h>
//============================================
//    WiringPi pin numbers
// 
//           --------------
//           |            |  5v
//           |            |
//           |            |  GND
//    Input  | 7          |
//           |            |
//    Pulse  | 0          |
//    Log    | 2          |
//    Online | 3          |
//           |            |
//           |            |
//           |            |
//           |            |
//           |            |
//           --------------
//
// gcc -Wall -o nabton nabton.c -lwiringPi -lm
//============================================

#define LED_PULSE    0
#define LED_INP      7
#define LED_LOG      2
#define LED_ONLINE   3

#define NT_POWER    1
#define NT_NETWORK  2
#define NT_INTERNET 3
#define NT_NABTON   4

FILE    *ofp;
int     first = 0;
int     p_year=0,p_month=0,p_day=0;
clock_t g_begin,g_now;
time_t  t;
struct  tm ldt;
// default config calues
int     g_prec       = 1; // 1=millisec 2=microsec
int     g_pulse_rate = 1000;
int     g_log_rate   = 15000; // 15 sec
int     g_cpar       = 5;

float   g_pow_now    = 0.;
float   g_mx_pow[90];
float   g_factor     = 3600000.; //   1000 pulse per kWh
//float   g_factor     = 360000.; // 10000 pulse per kWh
int     g_pulse      = 0;
int     g_debug      = 0;
int     g_server     = 1;
int     g_local      = 0;

struct  timeval start, end,start2, end2;
 
//===========================================
void errorMsg(char *msg)
//===========================================
{
   FILE    *in;
   time_t tm;
   struct tm *ltime;

   in = fopen("error.nab","a");
   // Timestamp with system time
   time( &tm );
   ltime = localtime( &tm );
   ltime->tm_mon++;
   ltime->tm_year += 1900;
   
   fprintf(in,"%d-%d-%d %d:%d:%d %s\n",ltime->tm_year,ltime->tm_mon,ltime->tm_mday,ltime->tm_hour,ltime->tm_min,ltime->tm_sec,msg);
   
   fclose(in);
}
//===========================================
void onlineConfig()
//===========================================
{
   FILE  *in;
   char  line[128],key[24];
   long  value = 99;

   in = fopen("download.nab","r");
   if(in == NULL)
   {
     digitalWrite (LED_ONLINE, LOW);
     errorMsg("Unable to open NABTON configuration file");
   }
   else
   {
         digitalWrite (LED_ONLINE, HIGH);
     while (fgets(line,sizeof line,in) != NULL)
     {
        sscanf(line,"%s %ld",key,&value);
        if(strcmp(key,"NT_PR") == 0) g_pulse_rate = value;
        if(strcmp(key,"NT_LR") == 0) g_log_rate   = value;
        if(strcmp(key,"NT_PR") == 0) g_prec       = (int)value;
        if(strcmp(key,"NT_ID") == 0) g_id         = (int)value;
     }
     fclose(in);
     // Bit 1: pulse rate 1000
     // Bit 2: pulse rate 10000
     // Bit 3: precision  1
     // Bit 4: precision  2
     if(g_pulse_rate == 1000 && g_prec == 1)  g_cpar = 5;
     if(g_pulse_rate == 1000 && g_prec == 2)  g_cpar = 9;
     if(g_pulse_rate == 10000 && g_prec == 1) g_cpar = 6;
     if(g_pulse_rate == 10000 && g_prec == 2) g_cpar = 10;
     
     if(g_pulse_rate == 1000)g_factor = 3600000.;
     if(g_pulse_rate == 10000)g_factor = 360000.;
     system("rm -f download.nab");
   }
}
//===========================================
void resetClock()
//===========================================
{
    gettimeofday(&start, NULL);
}
//===========================================
float checkClock(int prec)
//===========================================
{
    float ftime;
    long mtime, seconds, useconds;  
    gettimeofday(&end, NULL);
    seconds  = end.tv_sec  - start.tv_sec;
    useconds = end.tv_usec - start.tv_usec;
    if(prec==1)
    {
       mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
       ftime = (float)mtime;
    }
    if(prec==2)
    {
       mtime = ((seconds)*1000000 + useconds) + 0.5;
       ftime = mtime/1000.; // ms
    }
    //if(g_debug > 2)printf("C1 Elapsed time: %.3f\n", ftime);
    return(ftime);
}
//===========================================
void resetClock2()
//===========================================
{
    gettimeofday(&start2, NULL);
}
//===========================================
float checkClock2(int prec)
//===========================================
{
    float ftime;
    long mtime, seconds, useconds;  
    gettimeofday(&end2, NULL);
    seconds  = end2.tv_sec  - start2.tv_sec;
    useconds = end2.tv_usec - start2.tv_usec;
    if(prec==1)
    {
       mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
       ftime = (float)mtime;
    }
    if(prec==2)
    {
       mtime = ((seconds)*1000000 + useconds) + 0.5;
       ftime = mtime/1000.; // ms
    }
    //if(g_debug > 2)printf("C2 Elapsed time: %ld\n",mtime);
    return(ftime);
}
//===========================================
void getPulse()
//===========================================
{
  float  msec;
  float  power;

  g_pulse++;
  msec = checkClock(g_prec);
  resetClock();
  power = g_factor/msec;
  g_mx_pow[g_pulse] = power;
  g_pow_now = g_pow_now + power;
  //if(g_debug > 1 )printf("get pulse --- pow=%.3f  msec=%.3f\n",power,msec);
  digitalWrite (LED_PULSE, HIGH);
  delay(2);
  digitalWrite (LED_PULSE, LOW);
}
//===========================================
void blinkLed(int led, int nblink)
//===========================================
{
  int i;
        
  for (i=0;i<nblink;i++)
  {
         digitalWrite (LED_ONLINE, HIGH);
         delay(500);
         digitalWrite (LED_ONLINE, LOW);
         delay(500);
  }
}
//===========================================
void readIpAddress(char *ips)
//===========================================
{
  FILE  *in;
  char  line[128];
  char  temps[12];
  int   net=0;

  system("ifconfig > ipaddress.nab");
  delay(1000);
  in = fopen("ipaddress.nab","r");
  //printf("Open ip file\n");
  strcpy(ips,"no ip found");
  while (fgets(line,sizeof line,in) != NULL)
  { 
          if(strstr(line,"wlan") != NULL)
          {
             net = 1; //wlan
          }
          if(strstr(line,"eth") != NULL)
          {
             net = 2; //eth
          }
          if(strstr(line,"Loopback") != NULL)
          {
             net = 3; //lo
          }
          if(strstr(line,"inet addr:") != NULL)
          {
             if(net != 3)
             {
               sscanf(line,"%s %s",temps,ips);
             }
          }
  }
  fclose(in);
  if(strstr(ips,"no ip found")!= NULL)errorMsg("No IP Address");
  return;
}
//===========================================
//===========================================
int main (int argc, char **argv)
//===========================================
//===========================================
{
  FILE  *in;
  int try=0,state,i;
  float x;
  char sys[520],ip[180],sys2[120];
  time_t tm;
  struct tm *ltime;

  wiringPiSetup () ;
  piHiPri (0) ;
  
  pinMode (LED_PULSE,    OUTPUT) ;
  pinMode (LED_INP,      INPUT);
  pinMode (LED_LOG,      OUTPUT);
  pinMode (LED_ONLINE,   OUTPUT);


  state = NT_POWER;
  
  while(state != NT_NABTON)
  {
    digitalWrite (LED_PULSE, HIGH);
    digitalWrite (LED_LOG, HIGH);
    digitalWrite (LED_ONLINE, LOW);
  
    printf("NABTON Client connecting...%d\n",try);
    // Check if unit is connected to local network
    try = 0;
    while(state == NT_POWER)
    {
        try++;
        readIpAddress(ip);
        if(strstr(ip,"no ip found") == NULL) 
        {
              state = NT_NETWORK;
              digitalWrite (LED_PULSE, LOW);
        }
        printf("NABTON state=%d try=%d\n",state,try);
        delay(2000);
    }
  
    // Check if unit is connected to internet
    try = 0;
    while(state == NT_NETWORK)
    {
        try++;
        sprintf(sys,"wget -q -O internet.nab \"http://google.com\"");
        system(sys);    
        in = fopen("internet.nab","r");
        if(in != NULL)
        { 
              state = NT_INTERNET;
              digitalWrite (LED_LOG, LOW);
        }
        fclose(in);
        system("rm -f internet.nab");
        printf("NABTON state=%d try=%d\n",state,try);
        delay(2000);
    }
  
    // Check if unit is connected to nabton  
    try = 0;
    while(state == NT_INTERNET)
    {
        try++;
        sprintf(sys,"wget -q -O nabton.nab \"http://nabton.com/nabServer/server.php?user=%d&id=%d&ping=1\"",g_user,g_id);
        system(sys);     
        in = fopen("nabton.nab","r");
        if(in != NULL) 
        {
              state = NT_NABTON;
              digitalWrite (LED_ONLINE, HIGH);
        }
        fclose(in);
        system("rm -f nabton.nab");
        printf("NABTON state=%d try=%d\n",state,try);
        delay(2000);
     }
     
     if(state != NT_NABTON)
     {
        blinkLed(LED_ONLINE,try);
        delay(5000);
     }
  }

// Connection OK - continue logging power data
  if(state == NT_NABTON)
  {
    //INT_EDGE_FALLING, INT_EDGE_RISING, INT_EDGE_BOTH or INT_EDGE_SETUP
    wiringPiISR (LED_INP, INT_EDGE_FALLING, getPulse) ;

    for (;;)
    {
      delay(g_log_rate);
      if(g_pulse >= 10) // 10 samples before sending
      {
             x = g_pow_now/g_pulse; 
             // Auto adjust log rate
             g_log_rate = 1000.*3600./x; 
             digitalWrite (LED_LOG, HIGH);
             // Timestamp with system time
             time( &tm );
             ltime = localtime( &tm );
             ltime->tm_mon++;
             ltime->tm_year += 1900;
         sprintf(sys,"wget -q -O download.nab \"http://test.nabton.com/nabServer/server.php?user=%d&id=%d&cpar=%d&year=%d&month=%d&day=%d&hour=%d&min=%d&sec=%d&pulse=%d&pow=%.2f&data=",g_user,g_id,g_cpar,ltime->tm_year,ltime->tm_mon,ltime->tm_mday,ltime->tm_hour,ltime->tm_min,ltime->tm_sec,g_pulse,x);

         for(i=1;i<g_pulse;i++)
         {
                sprintf(sys2,"%.2f,",g_mx_pow[i]);
                strcat(sys,sys2);
         }
             sprintf(sys2,"%.2f",g_mx_pow[g_pulse]);
         strcat(sys,sys2);
             strcat(sys,"\"");

         g_pulse = 0;
         g_pow_now = 0.;
         //printf("Test %s\n",sys);
             system(sys);     
         onlineConfig();
         digitalWrite (LED_LOG, LOW);
      }
    }
  
  }
  return(0);
}
Show details
Terms - Privacy - Project Hosting Help
Powered by Google Project Hosting
